package com.ias.agdis_r.activity.task;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.bean.document.Document;
import com.ias.agdis_r.bean.document.DocumentResult;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.util.network.HttpUtil;
import com.ias.agdis_r.manager.BlueToothManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.bill.endpoint.request.BillDetailRequest;
import com.ias.agdis_r.terminalmanager.restful.bill.endpoint.request.BillPrintRequest;
import com.ias.agdis_r.terminalmanager.restful.bill.endpoint.response.BillDetailResponse;
import com.ias.agdis_r.terminalmanager.restful.bill.endpoint.response.BillGeneralResponse;
import com.ias.agdis_r.terminalmanager.restful.bill.vo.BillDetailRequestVO;
import com.ias.agdis_r.terminalmanager.restful.bill.vo.BillPrintRequestVO;
import com.ias.agdis_r.util.S;

/**
 * 单据详情界面
 * @author guoxr
 *
 */
public class TaskDocDetailActivity extends BaseActivity implements
		OnClickListener {
	private TextView txt_title;
	private TextView txt_content;
	private String fke;
	private String btp;
	private String tnb;
	private String fln;
	private String bno = "";
	private Document doc;
	private BillDetailRequest billdetailrequest;
	private ActionBar actionBar;
	private Intent intent;
	private BluetoothSocket btSocket;
	private OutputStream sendStream;
	private BillPrintRequest billprintRequest;
	private AlertDialog dialog;
	private Task task;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_taskdocdetail);
		actionBar = getActionBar();
		taskdocdetailactionbar();
		initGUI();
	}

	private void taskdocdetailactionbar() {
		// TODO Auto-generated method stub
		actionBar.setCustomView(LayoutInflater.from(TaskDocDetailActivity.this)
				.inflate(R.layout.actionbar_back_and_home, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		TextView title = (TextView) findViewById(R.id.txt_title);
		title.setText(R.string.TaskDocDetailActivity);
		ImageView back = (ImageView) findViewById(R.id.action_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		ImageView home = (ImageView) findViewById(R.id.action_home);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(TaskDocDetailActivity.this, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
	}

	private void initGUI() {
		Button button_back = (Button) findViewById(R.id.bottom_button1);
		Button button_sure = (Button) findViewById(R.id.bottom_button2);
		Button button_refresh = (Button) findViewById(R.id.bottom_button3);
		button_back.setOnClickListener(this);
		button_sure.setOnClickListener(this);
		button_refresh.setOnClickListener(this);
		button_back.setText(R.string.back);
		button_sure.setText(R.string.print);
		button_refresh.setText(R.string.refresh1);
		txt_title = (TextView) findViewById(R.id.detail_title);// 装载单内容
		txt_content = (TextView) findViewById(R.id.txt_TXT);// 装载单内容
		intent = getIntent();
		fln = S.valueOf(intent
				.getStringExtra(MessageModel.strTxtValue[MessageModel.nFLN]));
		fke = S.valueOf(intent.getStringExtra(MessageModel.FKE));
		btp = S.valueOf(intent.getStringExtra(MessageModel.BTP));
		tnb = S.valueOf(intent.getStringExtra(MessageModel.TNB));

        getDoc();
        this.bno = doc.getBNO();
        applyDocTxt();
        loadTtile();
		LinearLayout ll = (LinearLayout) findViewById(R.id.ll_button);
        if (S.isEmpty(tnb)) {
			ll.setVisibility(View.GONE);
		}
    }

    private void getDoc() {
        DocumentResult docResult = DataManager.getInstance().getDocList(fke);
        for (Document doc : docResult.getDocumentList()) {
            if (btp.equals(doc.getBTP())) {
                // TODO 保存doc
                this.doc = doc;
            }
        }
    }

	/**
	 * 申请单据内容
	 */
	public void applyDocTxt() {

		initBLDT(btp, fke);
		if (billdetailrequest != null) {
			HttpUtil.getInstance()
					.sendRequest(billdetailrequest, MessageModel.BLDT, false);
		} else {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,
					getString(R.string.noDoc), false);
		}
	}

	private void initBLDT(String btp, String fkey) {

		if (S.isNotEmpty(btp) && S.isNotEmpty(fkey)) {
			// TODO 申请单据信息
			billdetailrequest = new BillDetailRequest();
			BillDetailRequestVO billdetailrequestVO = new BillDetailRequestVO();
			if (S.isNotEmpty(doc.getBKE())) {
				billdetailrequestVO.setBke(doc.getBKE());
			}
			if (S.isNotEmpty(doc.getBNO())) {
				billdetailrequestVO.setBno(doc.getBNO());
			}
			if (S.isNotEmpty(btp)) {
				billdetailrequestVO.setBtp(btp);
			}
			billdetailrequestVO.setFkey(fkey);
			billdetailrequest.setBillDetailRequestVO(billdetailrequestVO);
		}
	}

	/**
	 * 申请单据内容
	 */
	private void loadTtile() {
		String title = "";
		String dnm = "";
		if (doc != null) {
			dnm = S.isEmpty(dnm) ? "" : dnm + ":";
		}
		title = dnm + fln;
		txt_title.setText(title);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.bottom_button1:
			finish();
			break;
		case R.id.bottom_button2:
			clickBtn2();
			break;
		case R.id.bottom_button3:
			applyDocTxt();
			break;
		default:
			break;
		}
	}

	public void clickBtn2() {
		// TODO Auto-generated method stub
		// 未获取到文本内容
		if (S.isEmpty(S.valueOf(txt_content.getText()))) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
					getString(R.string.reTryDoc), false);
			return;
		}
		// 不支持蓝牙
		if (!BlueToothManager.getInstance().BluetoothEnable()) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
					getString(R.string.bluetoothNotSupport), false);
			return;
		}
		// 蓝牙未打开时，打开蓝牙
		if (BlueToothManager.getInstance().getState() != BluetoothAdapter.STATE_ON) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
					getString(R.string.bluetoothNotOpen), false);
			BlueToothManager.getInstance().openBluetooth();
			return;
		}
		// 判断是否有已配对的蓝牙设备
		if (BlueToothManager.getInstance().hasPairedDevices()) {
			if (dialog == null || !dialog.isShowing()) {
				deviceDialog();
			}
		} else {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
					getString(R.string.noDevice), false);
			startActivity(new Intent(
					android.provider.Settings.ACTION_BLUETOOTH_SETTINGS));
		}
	}

	/**
	 * 选择已配对设备窗口
	 * **/
	private void deviceDialog() {
		// TODO Auto-generated method stub
		Set<BluetoothDevice> pairedDevices = BlueToothManager.getInstance()
				.getBondedDevices();
		final ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
		for (BluetoothDevice device : pairedDevices) {
			// 取出设备的名称和地址
			list.add(device);
		}
		ArrayList<String> nameList = new ArrayList<String>();
		for (int i = 0; i < list.size(); i++) {
			nameList.add(list.get(i).getName());
		}
		String[] strings = nameList.toArray(new String[nameList.size()]);
		AlertDialog.Builder bulider = new AlertDialog.Builder(
				TaskDocDetailActivity.this)
				.setTitle(getString(R.string.chooseDevice))
				.setIcon(android.R.drawable.ic_dialog_info)
				.setSingleChoiceItems(strings, 0,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
												int which) {
								BluetoothDevice dev = list.get(which);
								String name = dev.getName();
								String address = dev.getAddress();
								if (dev.getBondState() == BluetoothDevice.BOND_BONDED) {
									dialog.dismiss();
									print(name, address); // 打印
								} else if (dev.getBondState() == BluetoothDevice.BOND_BONDING) {
									EffectManager.getInstance().ttsPlay(
											EffectManager.TTS_TYPE_UPTO,
											getString(R.string.pairing), false);
								} else {
									EffectManager.getInstance().ttsPlay(
											EffectManager.TTS_TYPE_UPTO,
											getString(R.string.retry), false);
								}
							}
						}).setNegativeButton(getString(R.string.cancel), null);
		dialog = bulider.create();
		dialog.show();
	}

	private void print(String name, String address) {
		// TODO Auto-generated method stub
		BluetoothDevice btDev = BluetoothAdapter.getDefaultAdapter()
				.getRemoteDevice(address);
		if (btSocket == null) {
			try {
				Method m = btDev.getClass().getMethod("createRfcommSocket",
						new Class[] { int.class });
				btSocket = (BluetoothSocket) m.invoke(btDev, 1);
			} catch (Exception e) {
				e.printStackTrace();
				EffectManager.getInstance().ttsPlay(
						EffectManager.TTS_TYPE_UPTO, getString(R.string.printError), false);
			}
		}
		try {
			btSocket.connect();
			sendStream = btSocket.getOutputStream();
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
					getString(R.string.pairingSucceed), false);
		} catch (IOException e) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO,
					getString(R.string.pairingFailed), false);
			e.printStackTrace();
		}
		try {
			sendStream.write(doc.getTXT().getBytes("gbk"));
			setPrinter(4);
			setPrinter(3);
			openConfirmWindow();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK,
					getString(R.string.printFailed), false);
		}
		closeSocket();
	}

	private void closeSocket() {
		if (btSocket != null) {
			try {
				btSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			btSocket = null;
		}
	}

	/**
	 * 打开上报打印结果窗口
	 * **/
	public void openConfirmWindow() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				TaskDocDetailActivity.this);
		builder.setTitle(getString(R.string.printResult));
		builder.setMessage(getString(R.string.printMessage));
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				initBLPT(doc.getBKE(), doc.getBNO(), doc.getBTP(), fke);
				HttpUtil.getInstance().sendRequest(billprintRequest, MessageModel.BLPT,
						true);
				dialog.dismiss();
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	private void initBLPT(String bke, String bno, String btp, String fkey) {
		// TODO Auto-generated method stub
		billprintRequest = new BillPrintRequest();
		BillPrintRequestVO billprintRequestVO = new BillPrintRequestVO();
		billprintRequestVO.setBke(bke);
		billprintRequestVO.setBno(bno);
		billprintRequestVO.setBtp(btp);
		billprintRequestVO.setFkey(fkey);
		billprintRequest.setBillPrintRequestVO(billprintRequestVO);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (S.isNotEmpty(tnb)) {
			task = DataManager.getInstance().getWorkTask(tnb);
			if (null == task) {
				finish();
			}else if (task.getPID().equals(MessageModel.TCXX) || task.getPID().equals(MessageModel.TEND) || task.getPID().equals(MessageModel.TRJT)) {
				finish();
			}
		}
	}

	@Override
	protected void operateResponseSucess(String serviceId, BaseResponse response) {
		// TODO Auto-generated method stub

        if (serviceId.equals(MessageModel.BLDT)) {
            BillDetailResponse myresponse = (BillDetailResponse) response;
            String fkey = myresponse.getBillDetailResponse().getFkey();
            if (fkey.equals(fke)) {
                loadData();
            }
        }
        if (serviceId.equals(MessageModel.BLRQ)) {
            BillGeneralResponse myresponse = (BillGeneralResponse) response;
            String fkey = myresponse.getBillGeneraResponse().getFkey();
            if (fkey.equals(fke) && doc != null) {
                getDoc();
                String newBno = doc.getBNO();
                if (S.isNotEmpty(newBno) && newBno.compareTo(bno) > 0) {
                    EffectManager.getInstance().ttsPlay(
                            EffectManager.TTS_TYPE_UPTO, getString(R.string.newDoc), false);
                    applyDocTxt();
                }
            }
        }
    }

	@Override
	protected void updateUI(String tag) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void updateUI(String tag, String tnb) {
		if (tag.equals(MessageModel.REFRESH)) {
			if (tnb.equals(this.tnb) && task != null) {
				if(MessageModel.TEND.equals(task.getPID()) || MessageModel.TCXX.equals(task.getPID()) || task.getPID().equals(MessageModel.TRJT)){
					finish();
				}
			}
		}
	}

	/**
	 * 加载单据内容
	 */
	private void loadData() {

		if (doc != null) {
			// 显示doc的内容
			txt_content.setText(doc.getTXT());
		}

	}

	private boolean setPrinter(int Int) {
		byte[] arrayOfByte = null;
		switch (Int) {
		case 0: // 初始化打印机
			arrayOfByte = new byte[2];
			arrayOfByte[0] = 27;
			arrayOfByte[1] = 64;
			break;
		case 1: // 打印并走纸到下一打印位
			arrayOfByte = new byte[2];
			arrayOfByte[0] = 0x1d;
			arrayOfByte[1] = 0x0c;
			break;
		case 2: // 打印并走纸到下一页首
			arrayOfByte = new byte[1];
			arrayOfByte[0] = 12;
			break;
		case 3: // 打印并换行
			arrayOfByte = new byte[1];
			arrayOfByte[0] = 10;
			break;
		case 4: // 打印并回车
			arrayOfByte = new byte[1];
			arrayOfByte[0] = 13;
			break;
		case 5: // 移动打印位置到下一个水平制表位置
			arrayOfByte = new byte[1];
			arrayOfByte[0] = 9;
			break;
		case 6: // 选择缺省行间距
			arrayOfByte = new byte[2];
			arrayOfByte[0] = 27;
			arrayOfByte[1] = 50;
			break;
		case 7: // 弹出钱箱
			arrayOfByte = new byte[5];
			arrayOfByte[0] = 27;// Hex 1B 70 m t1 t2
			arrayOfByte[1] = 112;// Decimal 27 112 m t1 t2
			arrayOfByte[2] = 0;
			arrayOfByte[3] = 100;
			arrayOfByte[4] = 100;
			break;
		}
		setCommand(arrayOfByte);
		return true;
	}

	private boolean setCommand(byte[] ArrayOfByte) {
		try {
			sendStream.write(ArrayOfByte);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}
}
